package com.xzzz.irda.codegen.controller;

import com.xzzz.irda.codegen.pojo.TableDO;
import com.xzzz.irda.codegen.service.GeneratorService;
import com.xzzz.common.base.pojo.PageRes;
import com.xzzz.common.base.pojo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 代码生成器
 *
 * @author xzzz
 * 
 */
@Slf4j
@Controller
@RequestMapping("/tool/generator")
public class GeneratorController {

	@Autowired
	private GeneratorService generatorService;

	/**
	 * 访问 templates 目录下的 index.html 页面
	 *
	 * @return 返回 templates 目录下的 index.html 页面
	 */
	@RequestMapping({"/"})
	public String indexPage() {
		return "index";
	}

	/**
	 * 列表
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/list")
	public R<PageRes<TableDO>> list(String tableName) {
		return R.ok(generatorService.listTablesByTableName(tableName));
	}

	/**
	 * 生成代码
	 *
	 * @param tables   表名字符串，多个表用 “,” 隔开
	 * @param response 响应对象
	 */
	@RequestMapping("/code")
	public void code(String tables, HttpServletResponse response) {
		byte[] data = generatorService.generatorCode(tables.split(","));

		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");
		OutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
			outputStream.write(data);
			outputStream.flush();
		} catch (IOException e) {
			throw new RuntimeException("文件下载错误");
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					throw new RuntimeException("生成代码时，流关闭失败");
				}
			}
		}
	}
}
